package com.example.onlineanswer.controller;

import com.example.onlineanswer.common.api.CommonResult;
import com.example.onlineanswer.model.vo.CertificateVO;
import com.example.onlineanswer.service.CertificateService;
import com.example.onlineanswer.common.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/certificates")
public class CertificateController {

    @Autowired
    private CertificateService certificateService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取当前用户的所有证书列表
     * @param token 授权Token
     * @return 证书列表
     */
    @GetMapping("/my")
    public CommonResult<List<CertificateVO>> getMyCertificates(
            @RequestHeader("Authorization") String token) {
        try {
            String actualToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            if (userId == null) {
                return CommonResult.failed("无法从Token获取用户信息");
            }
            
            // 调用服务层方法获取用户所有证书
            List<CertificateVO> certificates = certificateService.getUserCertificates(userId);
            
            return CommonResult.success(certificates);
        } catch (Exception e) {
            log.error("Error processing getMyCertificates with token {}: {}", token, e.getMessage(), e);
            return CommonResult.failed("获取证书列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户在指定竞赛的证书
     * 如果证书不存在但用户符合资格，则动态生成
     * @param contestId 竞赛ID
     * @param token 授权Token
     * @return 单个证书VO 或 null
     */
    @GetMapping("/my/{contestId}")
    public CommonResult<CertificateVO> getMyCertificateForContest(
            @PathVariable Long contestId,
            @RequestHeader("Authorization") String token) {
        try {
            String actualToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            if (userId == null) {
                return CommonResult.failed("无法从Token获取用户信息");
            }
            CertificateVO certificate = certificateService.getUserCertificateForContest(userId, contestId);
            if (certificate == null) {
                // You might want to return a specific message or 204 No Content if no certificate exists
                // For now, success with null data indicates no certificate found or eligible
                return CommonResult.success(null, "用户在此竞赛中无符合条件的证书");
            }
            return CommonResult.success(certificate);
        } catch (Exception e) {
            log.error("Error processing getMyCertificateForContest for contestId {} with token {}: {}", contestId, token, e.getMessage(), e);
            return CommonResult.failed("获取证书失败: " + e.getMessage());
        }
    }

    /**
     * 下载证书文件
     *
     * @param certificateId 证书ID
     * @return 文件流
     */
    @GetMapping("/download/{certificateId}")
    public ResponseEntity<?> downloadCertificate(@PathVariable Long certificateId, @RequestHeader("Authorization") String token) { 
        try {
            String actualToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            if (userId == null) {
                return ResponseEntity.status(401).body(CommonResult.failed("无法从Token获取用户信息"));
            }

            Resource fileResource = certificateService.loadCertificateFile(certificateId, userId);
            if (fileResource == null) {
                log.warn("Certificate file not found or user {} not authorized for certificateId {}", userId, certificateId);
                return ResponseEntity.notFound().build();
            }
            
            String contentType = MediaType.IMAGE_PNG_VALUE;

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileResource.getFilename() + "\"")
                    .body(fileResource);
        } catch (Exception e) {
            log.error("Error processing downloadCertificate for certId {} with token {}: {}", certificateId, token, e.getMessage(), e);
            return ResponseEntity.status(500).body(CommonResult.failed("下载证书失败: " + e.getMessage()));
        }
    }
} 